﻿using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Microsoft.Extensions.Caching.Distributed;
using PetAdoptApi.Extensions;
using PetAdoptApi.Constants;
using PetAdoptApi.Database;
using Microsoft.EntityFrameworkCore;

namespace PetAdoptApi.Entity;

[Table("user")]
public class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MaxLength(30)]
    public string Name { get; set; } = default!;

    public static async ValueTask<User> BindAsync(HttpContext context)
    {
        var userIdStr = context.User.Claims.FirstOrDefault(i => i.Type == ClaimTypes.NameIdentifier)?.Value ?? throw new BadHttpRequestException("you are not authenticated");
        var cache = context.RequestServices.GetRequiredService<IDistributedCache>()!;
        var user =  await cache.GetValueAsync<User>(CacheKeys.UserIdPrefix + userIdStr) 
            ?? await context.RequestServices.GetRequiredService<AppDbContext>().Users.FirstOrDefaultAsync(u=> u.Id == int.Parse(userIdStr))
            ?? throw new BadHttpRequestException("server error");
        return user;
    }
}
